// pages/cart/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
      isChecked:true,
      isAllChecked:false,
      total:0,
      list:[
        {
          id:1,
          name:"大米",
          num:10,
          price:100,
          imgPath:"/static/images/img2.png",
          isChecked:false
        },
        {
          id:2,
          name:"芹菜",
          num:20,
          price:200,
          imgPath:"/static/images/img1.png",
          isChecked:false
        },
      ]
    },
    dec(e){
      var index = e.currentTarget.dataset.index;
      
      var val = `list[${index}].num`
      this.setData({
        [val]: this.data.list[index].num == 0 ? 0 : -- this.data.list[index].num
      })
      this.totalPrice();
    },
    totalPrice(){
      var total = this.data.list.reduce((total,current)=>{
        if(current.isChecked){
          return total + current.price*current.num
        }else{
          return total
        }
      },0)
      this.setData({
        total:total
      })
      console.log(total)
    },
    changeCount(e){
      var val = e.detail.value;
      console.log(val);
      if(val.length == this.data.list.length){  // 全选
        var newArr = JSON.parse(JSON.stringify(this.data.list));
        newArr.forEach(ele =>ele.isChecked = true);
        this.setData({
          isAllChecked:true,
          list:newArr
        })
      }else{
        // 列表项至少有一项未选中   我们需要做的就是把选中的checkbox数据项变成true
        // 1 . 如何拿到选中的checkbox数据项
        // this.data.list val  [{id:1},{id:2}] [2];
        this.data.list.forEach((ele,index) =>{
          if(val.includes(JSON.stringify(ele.id))){  //ele.id  val
            // var val1 = `${ele}.isChecked`
            var val1 = `list[${index}].isChecked`
            this.setData({
              [val1]:true
            })
            // return ele
          }else{
            var val1 = `list[${index}].isChecked`
            this.setData({
              [val1]:false
            })
            
          }
        })
        this.setData({
          isAllChecked:false
        })
      }
      this.totalPrice();
    },
    allEvents(){
      // 控制列表项选中与全部取消选中、
      if(this.data.isAllChecked){ // 全部取消选中
          var newArr = JSON.parse(JSON.stringify(this.data.list));
          newArr.forEach(ele =>ele.isChecked = false);
          this.setData({
            list:newArr,
            isAllChecked:false
          })
      }else{ // 全部选中
        var newArr = JSON.parse(JSON.stringify(this.data.list));
        newArr.forEach(ele =>ele.isChecked = true);
        this.setData({
          list:newArr,
          isAllChecked:true
        })
      }
      this.totalPrice()
    },
    checkboxChange(e){
      console.log(e)
    },
 
  })